package com.lcz.lcz_blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lcz.lcz_blog.entity.AddBlogBean;
import com.lcz.lcz_blog.entity.Blog;
import com.lcz.lcz_blog.entity.CollectTblogTuser;
import com.lcz.lcz_blog.entity.result.CommonPage;
import com.lcz.lcz_blog.entity.result.ResultBean;
import com.lcz.lcz_blog.entity.result.UpdateBlogBean;
import com.lcz.lcz_blog.exception.BusinessException;
import com.lcz.lcz_blog.exception.CodeEnum;
import com.lcz.lcz_blog.service.IBlogService;
import com.lcz.lcz_blog.service.ICollectTblogTuserService;
import com.lcz.lcz_blog.util.CheckUtil;
import com.lcz.lcz_blog.util.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 刘传政
 * @since 2022-01-17
 */
@RestController
@RequestMapping("/blog")
@Api(description = "博客管理")
public class BlogController {
    @Autowired
    IBlogService service;
    @Autowired
    ICollectTblogTuserService collectService;

    @PostMapping("add")
    @ApiOperation(value = "新增博客", notes = "新增博客")
    public ResultBean<Integer> add(@RequestBody AddBlogBean addBlogBean, @RequestHeader String token) {
        int userId = JWTUtils.getIdByToken(token);//这里是之前的拦截器放行的。所以一定正确
        CheckUtil.requireNotEmpty(addBlogBean.title, "标题不能为空");
        CheckUtil.requireNotEmpty(addBlogBean.content, "内容不能为空");
        CheckUtil.requireNotEmpty(addBlogBean.content, "userid不能为空");

        Blog blog = new Blog();
        blog.setTitle(addBlogBean.title);
        blog.setContent(addBlogBean.content);
        blog.setUserId(userId);
        LocalDateTime localDateTime = LocalDateTime.now();
        blog.setUpdateTime(localDateTime);
        blog.setCreateTime(localDateTime);
        boolean save = service.save(blog);
        return ResultBean.success(blog.getId());
    }

    @PostMapping("delete/{id}")
    @ApiOperation(value = "删除博客", notes = "删除博客")
    public ResultBean delete(@PathVariable int id, @RequestHeader String token) {
        int userId = JWTUtils.getIdByToken(token);//这里是之前的拦截器放行的。所以一定正确
        CheckUtil.requireNotEmpty(id, "blogId不能为空");
        Blog byId = service.getById(id);
        if (byId == null) {
            return ResultBean.fail(new BusinessException(CodeEnum.COMMON_FAIL_CODE, "删除失败"));
        } else {
            if (byId.getUserId() == userId) {
                boolean b = service.removeById(id);
                if (b) {
                    return ResultBean.success(null);
                } else {
                    return ResultBean.fail(new BusinessException(CodeEnum.COMMON_FAIL_CODE, "删除失败"));
                }
            } else {
                return ResultBean.fail(new BusinessException(CodeEnum.NO_PERMISSION));
            }
        }
    }

    @PostMapping("update")
    @ApiOperation(value = "修改博客", notes = "修改博客")
    public ResultBean update(@RequestHeader String token, @RequestBody UpdateBlogBean updateBlogBean) {
        int userId = JWTUtils.getIdByToken(token);//这里是之前的拦截器放行的。所以一定正确
        CheckUtil.requireNotEmpty(updateBlogBean.id, "blogId不能为空");
        Blog byId = service.getById(updateBlogBean.id);
        if (byId == null) {
            return ResultBean.fail(new BusinessException(CodeEnum.COMMON_FAIL_CODE, "修改失败"));
        } else {
            if (byId.getUserId() == userId) {
                Blog blog = new Blog();
                blog.setId(updateBlogBean.id);
                blog.setTitle(updateBlogBean.title);
                blog.setContent(updateBlogBean.content);
                blog.setUpdateTime(LocalDateTime.now());
                boolean b = service.updateById(blog);
                if (b) {
                    return ResultBean.success(null);
                } else {
                    return ResultBean.fail(new BusinessException(CodeEnum.COMMON_FAIL_CODE, "修改失败"));
                }
            } else {
                return ResultBean.fail(new BusinessException(CodeEnum.NO_PERMISSION));
            }
        }
    }

    @GetMapping("queryById/{id}")
    @ApiOperation(value = "查询博客", notes = "查询博客")
    public ResultBean<Blog> queryById(@PathVariable int id) {
        CheckUtil.requireNotEmpty(id, "blogId不能为空");
        Blog blog = service.queryBlogById(id);
        if (blog == null) {
            return ResultBean.fail(new BusinessException(CodeEnum.COMMON_FAIL_CODE, "查询博客失败"));
        } else {
            return ResultBean.success(blog);

        }
    }

    @PostMapping("queryAll")
    @ApiOperation(value = "查询所有博客", notes = "查询所有博客")
    public ResultBean<List<Blog>> queryAll() {
        List<Blog> blogs = service.queryAll();
        return ResultBean.success(blogs);
    }

    @PostMapping("query_page")
    @ApiOperation(value = "分页查询博客", notes = "分页查询博客")
    public ResultBean<CommonPage<Blog>> query_page(@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @RequestHeader String token) {
        int userId = JWTUtils.getIdByToken(token);//这里是之前的拦截器放行的。所以一定正确
        Page<Blog> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("update_time");
        IPage<Blog> blogIPage = service.queryPage(page, queryWrapper);
        CommonPage<Blog> blogCommonPage = new CommonPage<>();
        blogCommonPage.total = blogIPage.getTotal();
        blogCommonPage.currentPage = blogIPage.getCurrent();
        blogCommonPage.pageSize = blogIPage.getSize();
        //这样是多次查数据库
        /*for (Blog record : blogIPage.getRecords()) {
            QueryWrapper<CollectTblogTuser> collectQueryWrapper = new QueryWrapper<>();
            collectQueryWrapper.eq("blog_id", record.getId())
                    .eq("user_id", userId);
            CollectTblogTuser one = collectService.getOne(collectQueryWrapper);
            if (one == null) {
                //此人没收藏
                record.isMyCollected = 0;
            } else {
                record.isMyCollected = 1;
            }
        }*/
        //这样是少查数据库，多一些遍历
        QueryWrapper<CollectTblogTuser> collectQueryWrapper = new QueryWrapper<>();
        collectQueryWrapper.eq("user_id", userId);
        List<CollectTblogTuser> list = collectService.list(collectQueryWrapper);
        for (CollectTblogTuser collectTblogTuser : list) {
            for (Blog record : blogIPage.getRecords()) {
                if (collectTblogTuser.getBlogId() == record.getId()) {
                    //此人收藏了
                    record.isMyCollected = 1;
                }
            }
        }
        blogCommonPage.dataList = blogIPage.getRecords();
        return ResultBean.success(blogCommonPage);
    }

    @PostMapping("query_title")
    @ApiOperation(value = "搜索博客", notes = "搜索博客")
    public ResultBean<CommonPage<Blog>> query_title(@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("keywords") String keywords, @RequestHeader String token) {
        int userId = JWTUtils.getIdByToken(token);//这里是之前的拦截器放行的。所以一定正确
        Page<Blog> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .orderByDesc("update_time")
                .like("title", keywords);
        IPage<Blog> blogIPage = service.queryPage(page, queryWrapper);
        CommonPage<Blog> blogCommonPage = new CommonPage<>();
        blogCommonPage.total = blogIPage.getTotal();
        blogCommonPage.currentPage = blogIPage.getCurrent();
        blogCommonPage.pageSize = blogIPage.getSize();
        QueryWrapper<CollectTblogTuser> collectQueryWrapper = new QueryWrapper<>();
        collectQueryWrapper.eq("user_id", userId);
        List<CollectTblogTuser> list = collectService.list(collectQueryWrapper);
        for (CollectTblogTuser collectTblogTuser : list) {
            for (Blog record : blogIPage.getRecords()) {
                if (collectTblogTuser.getBlogId() == record.getId()) {
                    //此人收藏了
                    record.isMyCollected = 1;
                }
            }
        }
        blogCommonPage.dataList = blogIPage.getRecords();
        return ResultBean.success(blogCommonPage);
    }

    @PostMapping("collect")
    @ApiOperation(value = "收藏博客", notes = "收藏博客")
    public ResultBean collect(@RequestHeader String token, @Param("blogId") int blogId, @ApiParam(value = "类型. 1收藏 2取消收藏", required = true) @Param("type") int type) {
        int userId = JWTUtils.getIdByToken(token);//这里是之前的拦截器放行的。所以一定正确
        CheckUtil.requireNotEmpty(blogId, "blogId不能为空");
        Blog blog = service.getById(blogId);
        if (blog == null) {
            return ResultBean.fail(new BusinessException(CodeEnum.COMMON_FAIL_CODE, "博客不存在"));
        }
        QueryWrapper<CollectTblogTuser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("blog_id", blogId)
                .eq("user_id", userId);
        CollectTblogTuser one = collectService.getOne(queryWrapper);
        if (type == 1) {
            //收藏
            if (one != null) {
                //说明已经收藏了
                return ResultBean.success(null, "收藏成功");
            } else {
                CollectTblogTuser save = new CollectTblogTuser();
                save.setBlogId(blogId);
                save.setUserId(userId);
                boolean save1 = collectService.save(save);
                if (save1) {
                    return ResultBean.success(null, "收藏成功");
                } else {
                    return ResultBean.fail(new BusinessException(CodeEnum.COMMON_FAIL_CODE, "收藏失败"));
                }
            }

        } else if (type == 2) {
            if (one != null) {
                //说明已经收藏了
                boolean remove = collectService.remove(queryWrapper);
                if (remove) {
                    return ResultBean.success(null, "取消收藏成功");
                } else {
                    return ResultBean.fail(new BusinessException(CodeEnum.COMMON_FAIL_CODE, "取消收藏失败"));
                }
            } else {
                return ResultBean.success(null, "取消收藏成功");
            }

        } else {
            return ResultBean.fail(new BusinessException(CodeEnum.BAD_REQUEST.getCode(), "type错误"));
        }

    }

    @PostMapping("query_collects")
    @ApiOperation(value = "我的收藏", notes = "我的收藏")
    public ResultBean<CommonPage<Blog>> query_collects(@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @RequestHeader String token) {
        int userId = JWTUtils.getIdByToken(token);//这里是之前的拦截器放行的。所以一定正确
        Page<Blog> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .orderByDesc("update_time");
        IPage<Blog> blogIPage = service.queryCollectPage(page, queryWrapper, userId);
        CommonPage<Blog> blogCommonPage = new CommonPage<>();
        blogCommonPage.total = blogIPage.getTotal();
        blogCommonPage.currentPage = blogIPage.getCurrent();
        blogCommonPage.pageSize = blogIPage.getSize();
        for (Blog record : blogIPage.getRecords()) {
            //此人收藏了
            record.isMyCollected = 1;
        }
        blogCommonPage.dataList = blogIPage.getRecords();
        return ResultBean.success(blogCommonPage);
    }

    @PostMapping("query_my_added")
    @ApiOperation(value = "我的发布", notes = "我的发布")
    public ResultBean<CommonPage<Blog>> query_my_added(@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @RequestHeader String token) {
        int userId = JWTUtils.getIdByToken(token);//这里是之前的拦截器放行的。所以一定正确
        Page<Blog> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .orderByDesc("update_time")
                .like("user_id", userId);
        IPage<Blog> blogIPage = service.queryPage(page, queryWrapper);
        CommonPage<Blog> blogCommonPage = new CommonPage<>();
        blogCommonPage.total = blogIPage.getTotal();
        blogCommonPage.currentPage = blogIPage.getCurrent();
        blogCommonPage.pageSize = blogIPage.getSize();
        QueryWrapper<CollectTblogTuser> collectQueryWrapper = new QueryWrapper<>();
        collectQueryWrapper.eq("user_id", userId);
        List<CollectTblogTuser> list = collectService.list(collectQueryWrapper);
        for (CollectTblogTuser collectTblogTuser : list) {
            for (Blog record : blogIPage.getRecords()) {
                if (collectTblogTuser.getBlogId() == record.getId()) {
                    //此人收藏了
                    record.isMyCollected = 1;
                }
            }
        }
        blogCommonPage.dataList = blogIPage.getRecords();
        return ResultBean.success(blogCommonPage);
    }
}
